package gorm2mongo

import (
	"gitee.com/z1gotool/gorm2mongo/mongoplu"
	"gitee.com/z1gotool/gorm2mongo/z1mongo"
	"gitee.com/z1gotool/z1err"
	"github.com/DATA-DOG/go-sqlmock"
	"go.mongodb.org/mongo-driver/mongo"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

// Gen new gorm DB
//
// # Use z1AddField
//
// gitee.com/z1gotool/gormplugin/z1add_field
//
// err:=Z1DB.Use(&z1add_field.Z1AddField{})
//
// z1err.Check(err)
//
// gitee.com/z1gotool/gormplugin/z1util
//
// db = z1util.UpdateDBContext(
//
//	// `z1AddFieldInsert`,
//	`z1AddFieldWhere`,
//	map[string]interface{}{
//		`place_id`: 73501,
//	},
//	db,
//	false,
//
// )
func NewDB(dbInfo MongoInfo, gormConfig gorm.Config) (db *gorm.DB, mdb *mongo.Database, err error) {
	defer z1err.Handle(&err)

	{
		sqlDB, _, err := sqlmock.New()
		z1err.Check(err)

		dialector := mysql.New(mysql.Config{
			Conn:                      sqlDB,
			SkipInitializeWithVersion: true,
		})

		gormConfig.SkipDefaultTransaction = true

		if gormConfig.NamingStrategy == nil {
			gormConfig.NamingStrategy = schema.NamingStrategy{
				// TablePrefix:   "t_", // 表名前缀，`User` 的表名应该是 `t_users`
				SingularTable: true, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `t_user`
			}
		}

		dbTmp, err := gorm.Open(dialector, &gormConfig)
		z1err.Check(err)

		db = dbTmp
	}

	{
		tmp, err := z1mongo.Connect(dbInfo.Uri, dbInfo.DBName, dbInfo.Timeout, dbInfo.ClientMaxNum)
		z1err.Check(err)
		mdb = tmp
	}

	{
		// Add ToMongo plugin
		db.Use(&mongoplu.ToMongo{})
		// db = z1util.UpdateDBContext(`z1mongoShowQuery`, true, db, false)
		// db = z1util.UpdateDBContext(`z1mongoIgnoreCase`, true, db, false)
	}

	return
}

type MongoInfo struct {
	Uri          string //mongodb://localhost:27017, mongodb://username:password@localhost:27017
	DBName       string
	Timeout      uint64
	ClientMaxNum uint64
}
